#include <stdio.h>
#include <stdlib.h>

// 简化版的list_head实现
struct list_head {
    struct list_head *next, *prev;
};

#define LIST_HEAD_INIT(name) { &(name), &(name) }
#define LIST_HEAD(name) \
    struct list_head name = LIST_HEAD_INIT(name)

static inline void INIT_LIST_HEAD(struct list_head *list)
{
    list->next = list;
    list->prev = list;
}

static inline void __list_add(struct list_head *new,
                  struct list_head *prev,
                  struct list_head *next)
{
    next->prev = new;
    new->next = next;
    new->prev = prev;
    prev->next = new;
}

static inline void list_add(struct list_head *new, struct list_head *head)
{
    __list_add(new, head, head->next);
}

static inline void list_add_tail(struct list_head *new, struct list_head *head)
{
    __list_add(new, head->prev, head);
}

static inline void __list_del(struct list_head * prev, struct list_head * next)
{
    next->prev = prev;
    prev->next = next;
}

static inline void list_del(struct list_head *entry)
{
    __list_del(entry->prev, entry->next);
    entry->next = NULL;
    entry->prev = NULL;
}

#define list_for_each_entry(pos, head, member) \
    for (pos = container_of((head)->next, typeof(*pos), member); \
         &pos->member != (head); \
         pos = container_of(pos->member.next, typeof(*pos), member))

#define container_of(ptr, type, member) ({ \
        const typeof( ((type *)0)->member ) *__mptr = (ptr); \
        (type *)( (char *)__mptr - offsetof(type,member) );})

#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)

// 自定义数据结构
struct my_item {
    int data;
    struct list_head list;
};

int main() {
    // 初始化链表头
    LIST_HEAD(my_list);
    
    // 创建并添加三个节点
    struct my_item *item1 = malloc(sizeof(struct my_item));
    item1->data = 10;
    INIT_LIST_HEAD(&item1->list);
    list_add_tail(&item1->list, &my_list);
    
    struct my_item *item2 = malloc(sizeof(struct my_item));
    item2->data = 20;
    INIT_LIST_HEAD(&item2->list);
    list_add_tail(&item2->list, &my_list);
    
    struct my_item *item3 = malloc(sizeof(struct my_item));
    item3->data = 30;
    INIT_LIST_HEAD(&item3->list);
    list_add_tail(&item3->list, &my_list);
    
    // 遍历链表
    printf("链表内容:\n");
    struct my_item *pos;
    list_for_each_entry(pos, &my_list, list) {
        printf("数据: %d\n", pos->data);
    }
    
    // 删除第二个节点
    list_del(&item2->list);
    free(item2);
    
    // 再次遍历
    printf("\n删除后链表内容:\n");
    list_for_each_entry(pos, &my_list, list) {
        printf("数据: %d\n", pos->data);
    }
    
    // 清理剩余节点
    list_for_each_entry(pos, &my_list, list) {
        list_del(&pos->list);
        free(pos);
    }
    
    return 0;
}